package pub.wkq.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import pub.wkq.springframework.beans.BeansException;
import pub.wkq.springframework.beans.PropertyValue;
import pub.wkq.springframework.beans.PropertyValues;
import pub.wkq.springframework.beans.factory.DisposableBean;
import pub.wkq.springframework.beans.factory.InitializingBean;
import pub.wkq.springframework.beans.factory.config.AutowireCapableBeanFactory;
import pub.wkq.springframework.beans.factory.config.BeanDefinition;
import pub.wkq.springframework.beans.factory.config.BeanPostProcessor;
import pub.wkq.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * * 在 AbstractAutowireCapableBeanFactory 类中实现了Bean 的实例化操作 newInstance.,有构造函数入参的对象怎么处理？
 * * 在处理完 Bean 对象的实例化后，直接调用 addSingleton 方法存放到单例对象的缓存中去。
 * @author 21129
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String name, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, name, args);
            // 给 bean 填充属性
            applyPropertyValues(name, bean, beanDefinition);
            // 执行 Bean 的初始化方法 和 BeanPostProcessor 的前置后置处理方法。
            bean = initializeBean(name, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        // 注册实现了 DisposableBean 接口的 Bean 对象
        registerDisposableBeanIfNecessary(name, bean, beanDefinition);

        addSingleton(name, bean);
        return bean;
    }

    private void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
        }
    }

    private Object initializeBean(String name, Object bean, BeanDefinition beanDefinition) {
        //1. 执行 BeanPostProcessor Before 处理
        Object wrappedBean =  applyBeanPostProcessorBeforeInitialization(bean, name);
        
        // 待完成内容 invokeInitMethods ( beanName,wrappedBean.beanDefinition)
        try {
            invokeInitMethods(name, wrappedBean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Invocation of init method of bean[" + name + "] failed", e);
        }

        //2. 执行 BeanPostProcessor After 处理
        wrappedBean = applyBeanPostProcessorAfterInitialization(bean, name);
        return wrappedBean;
    }
    @Override
    public Object applyBeanPostProcessorBeforeInitialization(Object existingBean, String name) {
        Object result = existingBean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object current = beanPostProcessor.postProcessBeforeInitialization(result, name);
            if (null == current ) return result;
            result = current;
        }
        return result;

    }
    @Override
    public Object applyBeanPostProcessorAfterInitialization(Object existingBean, String name) {
        Object result = existingBean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object current = beanPostProcessor.postProcessAfterInitialization(result, name);
            if (null == current ) return result;
            result = current;
        }
        return result;
    }

    private void invokeInitMethods(String name, Object wrappedBean, BeanDefinition beanDefinition) throws Exception {
        //1. 实现接口 InitializingBean
        if (wrappedBean instanceof InitializingBean) {
            ((InitializingBean) wrappedBean).afterPropertiesSet();
        }
        //2. 配置信息 init-method {判断是为了二次执行销毁}
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)) {
            Method initMethod = beanDefinition.getBeanClass().getMethod(initMethodName);
            if (null == initMethod) {
                throw new BeansException("Could not find an init method named'" + initMethodName + "' on bean with name '" + name + "'");
            }
            initMethod.invoke(wrappedBean);
        }
    }

    /**
     * Bean 属性填充
     * @param beanName beanName
     * @param bean bean 对象
     * @param beanDefinition bean 定义
     */
    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    // A 依赖 B ，获取 B 的实例化
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                // 属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values:" + beanName);
        }
    }

    private Object createBeanInstance(BeanDefinition beanDefinition, String name, Object[] args) {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            if (null != args && declaredConstructor.getParameterTypes().length == args.length) {
                constructorToUse = declaredConstructor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition, name, constructorToUse, args);
    }

    private InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }
}
